package com.jxwifi.cloud.quickcleanserver.upgrade;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.idroid.utils.MToast;
import com.idroid.utils.NoDoubleClickListener;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.SystemBean;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.OkHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.utils.DetectionUtils;
import com.jxwifi.cloud.quickcleanserver.utils.KAlertDialog;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 升级
 * Created by Administrator on 2019/5/24.
 */

public class UpgradeNotice {

    private static String TAG = "UpgradeNotice";
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private static int mFlag = 1;//1表示app自动检测更新，0表示手动点击更新按钮
    private static Activity mActivity;

    private static boolean mForceUpdate=false;//是否为强制更新
    private static String mStrversion="";//服务器版本号
    private static String mContent="";//更新内容
    private static String mDownLoadUrl="";//升级下载路径
    // 应用宝 360手机助手 百度手机助 机锋应用市场  小米应用商店 华为应用市场  OPPO应用商店 VIVO应用商店
    public static String[] market={"com.tencent.android.qqdownloader","com.qihoo.appstore","com.baidu.appsearch",
            "com.mappn.gfan","com.xiaomi.market","com.huawei.appmarket","com.oppo.market","com.bbk.appstore"};
    public static String mStrMarKet="";//获取手机应用中是否有安装的程序

    /**
     * @param context
     * @param mTAG
     * @param flag 1表示app自动检测更新，0表示手动点击更新按钮
     * @param ac
     */
    public static void UpgradeData( final Context context,final String mTAG,final int flag,final Activity ac){
        mActivity = ac;
        mFlag = flag;
        OkHttp.version = UpgradeCodeName.getVerName(context);
        Params params = new Params();
        //Log.i(TAG,"Start UpgradeData");
        AuzHttp.get(UrlPool.SYSTEM_LIST, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code==0){
                    List<SystemBean> msystemBean = JSON.parseArray(data, SystemBean.class);
                    for (int i = 0; i < msystemBean.size(); i++) {
                        if ("kjb_cleaner_version_force".equals(msystemBean.get(i).getKeyName())) {
                            if (msystemBean.get(i).getKeyValue().equals("0")){
                                mForceUpdate=false;
                            }else{
                                mForceUpdate=true;
                            }
                        }else if ("kjb_cleaner_version".equals(msystemBean.get(i).getKeyName())){
                            mStrversion = msystemBean.get(i).getKeyValue();
                        }else if ("kjb_cleaner_version_detail".equals(msystemBean.get(i).getKeyName())){
                            mContent = msystemBean.get(i).getKeyValue();
                        }else if ("kjb_cleaner_apk".equals(msystemBean.get(i).getKeyName())){
                            mDownLoadUrl=msystemBean.get(i).getKeyValue();
                        }
                    }
                    int mVersion = UpgradeCodeName.compareVersion(UpgradeCodeName.getVerName(context), mStrversion);
                    //Log.i(TAG,"getVerName = "+UpgradeCodeName.getVerName(context)+" mStrversion = "+mStrversion +" mVersion = "+mVersion);

                    if (mVersion == 0) {
                        if (flag == 0)
                            Toaster.show(context, "当前版本为最新版本");
                        return;
                    }else if (mVersion == 1) {
                        return;
                    }
                    if (null == context) return;
                    if (context instanceof Activity) {
                        if (((Activity) context).isFinishing()) return;
                    }

                    UploadDialog.Builder builder = new UploadDialog.Builder(context);
                    builder.setMessage(mContent, mStrversion, "");
                    builder.setPositiveButton("以后再说", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (mForceUpdate) { // 是否强制更新
                                //设置你的操作事项
                                Toaster.show(context, "抱歉,当前版本必须升级");
                                LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("exit_app"));
                            } else {
                                dialog.dismiss();
                                //EventBus.getDefault().post(true, "e-StopDismiss");//这个判断用于广告页面是否做升级操作
                            }
                        }
                    });

                    builder.setNegativeButton("立即更新",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    for (int i=0;i<market.length;i++){
                                        if (DetectionUtils.isAvilible(context,market[i])){
                                            mStrMarKet=market[i];
                                            break;
                                        }
                                    }
                                    //判断手机种是否有安装需要得各个平台，没有直接下载升级
                                    if("".equals(mStrMarKet)){
                                        int permission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                                        if (permission != PackageManager.PERMISSION_GRANTED) {
                                            // We don't have permission so prompt the user
                                            ActivityCompat.requestPermissions(
                                                    mActivity,
                                                    PERMISSIONS_STORAGE,
                                                    REQUEST_EXTERNAL_STORAGE
                                            );
                                            MToast.shortToast(context,"存储服务已关闭，请允许后再操作", Gravity.CENTER);
                                        } else {
                                            if (mForceUpdate) { //当为强制升级的时候，显示个弹框，不给用户操作
                                                final KAlertDialog dialogshow=new KAlertDialog(context,"更新到最新版本才能继续使用");
                                                dialogshow.leftTxtGone();
                                                dialogshow.setRightTxt("确定", new NoDoubleClickListener() {
                                                    @Override
                                                    protected void onNoDoubleClick(View v) {
                                                        LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("exit_app"));
                                                    }
                                                });
                                                dialogshow.setCancelable(false);
                                                dialogshow.show();
                                            }
                                            if (!isServiceRunning(context,"com.jxwifi.cloud.quickcleanserver.upgrade.UpdateService")){
                                                Log.w("oushuhua","com.jxwifi.cloud.quickcleanserver   true");
                                                Intent updateIntent =new Intent(context, UpdateService.class);
                                                updateIntent.putExtra("app_name", "快洁帮专员");
                                                updateIntent.putExtra("downurl",mDownLoadUrl);
                                                Log.w("oushuhua","mDownLoadUrl=="+mDownLoadUrl);
                                                context.startService(updateIntent);
                                            }
                                            dialog.dismiss();
                                        }
                                    }else{
                                        launchAppDetail("com.jxwifi.cloud.quickcleanserver",mStrMarKet,context);
                                    }
                                }
                            });
                    builder.create().show();

                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Log.i(TAG, "UpgradeData starts onFailure");
                Toast toast =Toast.makeText(context, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        },mTAG);
    }

    // 判断服务是否开启
    public static boolean isServiceRunning(Context context, String ServiceName) {
        if (("").equals(ServiceName) || ServiceName == null)
            return false;
        ActivityManager myManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(ServiceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 启动到应用商店app详情界面
     * @param appPkg    目标App的包名
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public static void launchAppDetail(String appPkg, String marketPkg,Context context) {
        try {
            if (TextUtils.isEmpty(appPkg)) return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
